##############################################################
##############################################################
### Replication Materials for
### Stefan Müller and Liam Kneafsey:
### Evidence for the Irrelevance of Irrelevant Events
### Political Science Research and Methods
###
### Please get in touch with the authors if you have any questions: 
### stefan.mueller@ucd.ie
### Note: 0000_readme.pdf contains 
### instructions and details about each script and dataset
##############################################################
##############################################################

## load packages
library(dplyr)        # CRAN v1.0.5
library(tidyr)        # CRAN v1.1.3
library(stringr)      # CRAN v1.4.0
library(ggplot2)      # CRAN v3.3.3
library(estimatr)     # CRAN v0.30.2
library(ggeffects)    # CRAN v1.0.1
library(modelsummary) # CRAN v0.8.0
library(here)         # CRAN v1.0.1

here::here()
## alternatively, set working directory manually
# setwd("...")

## load code for default plotting scheme
source("function_theme_base.R")


## function to create a ggplot2 plot that plots the interaction 
## between match treatment (defeat, untreated, win) and incumbency status
plot_interaction <- function(x, 
                             axis_title = "Expected change in vote share\n(percentage points)") {
    
    data <- x
    
    data$winner_loser_untreated <- factor(data$x,
                                          levels = c("Defeat", 
                                                     "Untreated", 
                                                     "Win"))
    
    
    data$group <- factor(data$group,
                         levels = c("Incumbent (Candidate elected in t-1)", 
                                    "Challenger (Candidate not elected in t-1)"))
    
    ggplot(data, 
           aes(x = winner_loser_untreated,
               y = predicted,
               colour = winner_loser_untreated)) +
        geom_hline(yintercept = 0, colour = "grey30", size = 1, 
                   linetype = "dashed") +
        facet_grid(~group) +
        geom_linerange(aes(ymin = predicted - 1.96 * std.error,
                           ymax = predicted + 1.96 * std.error),
                       size = 0.5) +
        geom_linerange(aes(ymin = predicted - 1.645 * std.error,
                           ymax = predicted + 1.645 * std.error),
                       size = 1.3) +
        geom_point(size = 4) + 
        scale_y_continuous(limits = c(-3, 3),
                           breaks = c(seq(-3, 3, 1))) +
        scale_colour_manual(values = c("darkred", "black", "darkgreen")) +
        labs(x = NULL, y = axis_title) +
        theme(legend.position = "none")
    
}


## Prepare data with local and general election results ----

## load local election results
dat_local <- readRDS("data_elections_local_full.rds") 


## check how often each candidate-party-constituency observation
## is in the dataset (some candidates appear twice because their constituency
## was matched to two counties (e.g., Carlow-Kilkenny -> team Carlow and Kilkenny)
dat_local <- dat_local %>% 
    group_by(const_link, party, date, candidate) %>% 
    mutate(n_obs = n()) %>% 
    select(n_obs, everything()) %>% 
    arrange(-n_obs) %>% 
    ungroup() %>% 
    mutate(election_id = as.factor(election_id)) %>% 
    mutate(party_recoded = as.character(party_recoded)) %>% 
    mutate(county_gaa = as.character(county_gaa))



## load data for general elections
dat_general <- readRDS("data_elections_general_full.rds")

## change coding of some variables
dat_general <- dat_general %>% 
    mutate(election_id = as.factor(election_id)) %>% 
    mutate(party_recoded = as.character(party_recoded)) %>% 
    mutate(county_gaa = as.character(county_gaa))


## check how often each candidate-party-constituency observation
## is in the dataset (some candidates appear twice because their constituency
## was matched to two counties (e.g., Carlow-Kilkenny -> team Carlow and Kilkenny)
dat_general <- dat_general %>% 
    group_by(constituency_link, party, date, candidate) %>% 
    mutate(n_obs = n()) %>% 
    select(n_obs, everything()) %>% 
    arrange(-n_obs) %>% 
    ungroup()

## relevel factors for incumbency
dat_general$incumbency_status_party <- relevel(factor(dat_general$incumbency_status_party), 
                                               ref = 2)


table(dat_general$incumbency_status_party)

## get summary statistics on dependent variable
dat_local %>% 
    summarise(mean_change = mean(diff_share),
              sd = sd(diff_share))

dat_general %>% 
    ungroup() %>% 
    summarise(mean_change = mean(diff_share),
              sd = sd(diff_share))


## relevel factors
dat_general$winner_loser_before <- factor(dat_general$winner_loser_before,
                                          levels = c("Defeat", "Untreated", "Win"))

dat_local$winner_loser_before <- factor(dat_local$winner_loser_before,
                                        levels = c("Defeat", "Untreated", "Win"))


## only select "treated" candidates
dat_general_treated <- filter(dat_general, winner_loser_before != "Untreated")


dat_local_treated <- filter(dat_local, winner_loser_before != "Untreated")

table(dat_general$difference,
      dat_general$winner_loser_before)


## analyse number of matches that took place shortly before elections

length(unique(dat_general$match_id))

length(unique(dat_local$match_id))


##  Regression Models ----

lm_cand_share_general_base <- estimatr::lm_robust(
    diff_share ~ 
        winner_loser_before * incumbent,
    clusters = county_gaa,
    se_type = "stata",
    data = dat_general)


## for comparison, rerun model without clustered standard errors
lm_cand_share_general_noclusters <- estimatr::lm_robust(
    diff_share ~ 
        winner_loser_before * incumbent,
    se_type = "stata",
    data = dat_general)



## rerun model for local elections
lm_cand_share_local_base <- update(
    lm_cand_share_general_base, 
    data = dat_local)


## run model for general elections with more fixed effects
lm_cand_share_general_all <- estimatr::lm_robust(
    diff_share ~ 
        winner_loser_before * incumbent +
        party_recoded + election_id + 
        county_gaa,
    clusters = county_gaa,
    se_type = "stata",
    data = dat_general)


## repeat for local elections
lm_cand_share_local_all <- update(
    lm_cand_share_general_all,
    data = dat_local)


## only select treated candidates in general elections
lm_cand_share_general_treated <- update(
    lm_cand_share_general_all,
    data = dat_general_treated)


## only select treated candidates in local elections
lm_cand_share_local_treated <- update(
    lm_cand_share_general_all,
    data = dat_local_treated)


## Table 01 ----

models_main <- list()
models_main[['M1: General elections']] <- lm_cand_share_general_base
models_main[['M2: General elections']] <- lm_cand_share_general_all
models_main[['M3: Local elections']] <- lm_cand_share_local_base
models_main[['M4: Local elections']] <- lm_cand_share_local_all

rename_coefs <- c("Intercept" = "(Intercept)",
                  "winner_loser_beforeUntreated" = "Untreated (ref. = Defeat)",
                  "winner_loser_beforeWin" = "Win",
                  "incumbentIncumbent (Candidate elected in t-1)" = "Candidate elected in t-1",
                  "winner_loser_beforeUntreated:incumbentIncumbent (Candidate elected in t-1)" = "Untreated : Candidate elected in t-1",
                  "winner_loser_beforeWin:incumbentIncumbent (Candidate elected in t-1)" = "Win : Candidate elected in t-1")


rows_add_4 <- tribble(~term, ~m1, ~m2, ~m3, ~m4,
                      'Election FE', '', '✓', '', '✓',
                      'Party FE', '', '✓', '', '✓', 
                      'County FE', '', '✓', '', '✓')
attr(rows_add_4, 'position') <- c(11, 12, 13)

## print table in Viewer pane
modelsummary(models_main,
             add_rows = rows_add_4,
             statistic = "conf.int",
             fmt = "%.2f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs,
             gof_omit = "se_type",
             align = "lll")

modelsummary(models_main,
             add_rows = rows_add_4,
             statistic = "conf.int",
             fmt = "%.2f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs,
             gof_omit = "se_type",
             align = "lll",
             output = "tab_01.docx")



## Figure 01 ----

str(dat_general$election_id)

dat_eff_share_general <- ggpredict(lm_cand_share_general_base,
                                   terms = c("winner_loser_before",
                                             "incumbent"))

plot_interaction(dat_eff_share_general)
ggsave("fig_01.pdf", 
       width = 9, height = 3.5)


## Figure 02 ----

dat_eff_share_local <- ggpredict(lm_cand_share_local_base,
                                 terms = c("winner_loser_before",
                                           "incumbent"))

plot_interaction(dat_eff_share_local)
ggsave("fig_02.pdf", 
       width = 9, height = 3.5)



## models for general elections: change in support for candidates 
## from government/opposition parties (measured as government status at the time of the election)

lm_govstatus_share_general_base <- estimatr::lm_robust(
    diff_share ~ 
        winner_loser_before * incumbency_status_party,
    clusters = county_gaa,
    se_type = "stata",
    data = dat_general)



lm_govstatus_share_general_all <- estimatr::lm_robust(
    diff_share ~ 
        winner_loser_before * incumbency_status_party +
        party_recoded + 
        election_id + county_gaa,
    clusters = county_gaa,
    se_type = "stata",
    data = dat_general)


## Table 02 ----
model_govstatus <- list()
model_govstatus[['M1: General elections']] <- lm_govstatus_share_general_base
model_govstatus[['M2: General elections']] <- lm_govstatus_share_general_all


rename_coefs_govstatus <- c("Intercept" = "(Intercept)",
                            "winner_loser_beforeUntreated" = "Untreated (ref. = Defeat)",
                            "winner_loser_beforeWin" = "Win",
                            "incumbency_status_partyParty: Government" = "Candidate's party in government",
                            "winner_loser_beforeUntreated:incumbency_status_partyParty: Government" = "Untreated x Candidate's party in government",
                            "winner_loser_beforeWin:incumbency_status_partyParty: Government" = "Win x Candidate's party in government")


rows_add_govstatus <- tribble(~term, ~m1, ~m2,
                              'Election FE', '', '✓', 
                              'Party FE', '', '✓',
                              'County FE', '', '✓',
)

attr(rows_add_govstatus, 'position') <- c(11, 12, 13)

modelsummary(model_govstatus,
             statistic = "conf.int",
             fmt = "%.2f",
             add_rows = rows_add_govstatus,
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_recoded*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs_govstatus,
             gof_omit = "se_type",
             align = "lll")

modelsummary(model_govstatus,
             statistic = "conf.int",
             fmt = "%.2f",
             add_rows = rows_add_govstatus,
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_recoded*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs_govstatus,
             gof_omit = "se_type",
             align = "lll",
             output = "tab_02.docx")



## Figure 03 ----

dat_eff_govstatus_share <- ggpredict(lm_govstatus_share_general_base,
                                     terms = c("winner_loser_before",
                                               "incumbency_status_party"))


dat_eff_govstatus_share$winner_loser_untreated <- factor(dat_eff_govstatus_share$x,
                                                         levels = c("Defeat", 
                                                                    "Untreated", 
                                                                    "Win"))


dat_eff_govstatus_share$group <- relevel(factor(dat_eff_govstatus_share$group),
                                         ref = 2)


ggplot(dat_eff_govstatus_share, 
       aes(x = winner_loser_untreated,
           y = predicted,
           colour = winner_loser_untreated)) +
    geom_hline(yintercept = 0, colour = "grey30", size = 1, 
               linetype = "dashed") +
    facet_grid(~group) +
    geom_linerange(aes(ymin = predicted - 1.96 * std.error,
                       ymax = predicted + 1.96 * std.error),
                   size = 0.5) +
    geom_linerange(aes(ymin = predicted - 1.645 * std.error,
                       ymax = predicted + 1.645 * std.error),
                   size = 1.3) +
    geom_point(size = 4) + 
    scale_y_continuous(limits = c(-3, 3),
                       breaks = c(seq(-3, 3, 1))) +
    scale_colour_manual(values = c("darkred", "black", "darkgreen")) +
    labs(x = NULL, y = "Expected change in vote share\n(percentage points)") +
    theme(legend.position = "none")
ggsave("fig_03.pdf", 
       width = 9, height = 3.5)



## Robustness: Regression Models ----

## rerun models using absolute changes in votes

lm_cand_votes_general_base <- estimatr::lm_robust(
    diff_votes ~ 
        winner_loser_before * incumbent,
    clusters = county_gaa,
    se_type = "stata",
    data = dat_general)


lm_cand_votes_local_base <- update(
    lm_cand_votes_general_base, 
    data = dat_local)

lm_cand_votes_general_all <- estimatr::lm_robust(
    diff_votes ~ 
        winner_loser_before * incumbent +
        party_recoded + election_id + county_gaa,
    clusters = county_gaa,
    se_type = "stata",
    data = dat_general)


lm_cand_votes_local_all <- update(
    lm_cand_votes_general_all,
    data = dat_local)


## Table A3 ----
models_votes <- list()
models_votes[['M1: General elections (votes)']] <- lm_cand_votes_general_base
models_votes[['M2: General elections (votes)']] <- lm_cand_votes_general_all
models_votes[['M3: Local elections (votes)']] <- lm_cand_votes_local_base
models_votes[['M4: Local elections (votes)']] <- lm_cand_votes_local_all


modelsummary(models_votes,
             add_rows = rows_add_4,
             statistic = "conf.int",
             fmt = "%.1f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs,
             gof_omit = "se_type",
             align = "lll")

modelsummary(models_votes,
             add_rows = rows_add_4,
             statistic = "conf.int",
             fmt = "%.1f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs,
             gof_omit = "se_type",
             align = "lll",
             output = "tab_a03.docx")



## Figure A08 ----
dat_eff_votes_general<- ggpredict(
    lm_cand_votes_general_base,
    terms = c("winner_loser_before",
              "incumbent"))


plot_interaction(dat_eff_votes_general,
                 axis_title = "Expected change in votes (absolute)") +
    scale_y_continuous(limits = c(-800, 1300))
ggsave("fig_a08.pdf", 
       width = 9, height = 3.5)


## Figure A09 ----
dat_eff_votes_local <- ggpredict(lm_cand_votes_local_base,
                                 terms = c("winner_loser_before",
                                           "incumbent"))

plot_interaction(dat_eff_votes_local,
                 axis_title = "Expected change in votes (absolute)") +
    scale_y_continuous(limits = c(-250, 250))
ggsave("fig_a09.pdf", 
       width = 9, height = 3.5)



## Descriptive plots on elections and candidates for Supporting Information ----

dat_general_describe <- select(dat_general, -year_lag)

dat_general_describe$type_election <- "General elections"
dat_general_describe$election_year <- factor(dat_general_describe$election_year)
dat_general_describe$elected <- factor(dat_general_describe$elected)

dat_local_describe <- select(dat_local, -year_lag)

dat_local_describe$type_election <- "Local elections"
dat_local_describe$election_year <- factor(dat_local_describe$election_year)
dat_local_describe$elected <- factor(dat_local_describe$elected)


dat_merged <- bind_rows(dat_general_describe, dat_local_describe)


dat_sum_general <- dat_general_describe %>% 
    ungroup() %>% 
    filter(!is.na(diff_share)) %>% 
    group_by(winner_loser_before) %>%
    summarise(n = n()) %>%
    mutate(relfreq = n / sum(n)) %>% 
    mutate(type = "General elections")

dat_sum_local <- dat_local_describe %>% 
    ungroup() %>% 
    filter(!is.na(diff_share)) %>% 
    group_by(winner_loser_before) %>%
    summarise(n = n()) %>%
    mutate(relfreq = n / sum(n)) %>% 
    mutate(type = "Local elections")


dat_sum_combined <- bind_rows(dat_sum_local, dat_sum_general)

dat_sum_combined$winner_loser_before <- factor(
    dat_sum_combined$winner_loser_before, 
    levels = c("Defeat", "Win", "Untreated")
)

## Figure A03 ----
ggplot(dat_sum_combined, aes(x = winner_loser_before,
                             y = relfreq, fill = winner_loser_before)) +
    geom_bar(stat = "identity", width = 0.6) +
    geom_text(aes(label = n), nudge_y = 0.04, size = 4) +
    scale_fill_manual(values = c("darkred", "darkgreen", "grey30")) +
    scale_y_continuous(limits = c(0, 1), labels = scales::percent_format(accuracy = 1)) +
    facet_wrap(~type) +
    labs(x = NULL, y = "Percentage of observations within group") +
    theme(legend.position = "none")
ggsave("fig_a03.pdf", 
       width = 9, height = 3.5)


## get number of candidates with win/defeated/untreated condition
## for each general election

dat_sum_winner_loser_general <- dat_general_describe %>% 
    group_by(election_id) %>% 
    count(winner_loser_before) %>% 
    filter(n > 0)

dat_sum_winner_loser_general$winner_loser_before <- factor(
    dat_sum_winner_loser_general$winner_loser_before, 
    levels = c("Win", "Defeat", "Untreated")
)

## Figure A04 ----
set.seed(135)
ggplot(dat_sum_winner_loser_general, aes(x = factor(election_id), 
                                         y = n,
                                         colour = winner_loser_before,
                                         shape = winner_loser_before)) +
    geom_point(size = 2) +
    facet_wrap(~winner_loser_before, nrow = 1) +
    coord_flip() +
    ggrepel::geom_text_repel(aes(label = n)) +
    scale_colour_manual(values = c("darkgreen", "darkred", "grey30")) +
    scale_shape_manual(values = c(16, 1, 17)) +
    theme(legend.position = "none") +
    labs(x = NULL, y = "Number of observations")
ggsave("fig_a04.pdf", 
       width = 9, height = 6)


## get number of candidates with win/defeated/untreated condition
## for each local election

dat_sum_winner_loser_local <- dat_local_describe %>% 
    group_by(election_id) %>% 
    count(winner_loser_before) %>% 
    filter(n > 0)

dat_sum_winner_loser_local$winner_loser_before <- factor(
    dat_sum_winner_loser_local$winner_loser_before, 
    levels = c("Win", "Defeat", "Untreated")
)

## Figure A05 ----
set.seed(35)
ggplot(dat_sum_winner_loser_local, aes(x = factor(election_id), 
                                       y = n,
                                       colour = winner_loser_before,
                                       shape = winner_loser_before)) +
    geom_point(size = 2) +
    facet_wrap(~winner_loser_before, nrow = 1) +
    coord_flip() +
    ggrepel::geom_text_repel(aes(label = n)) +
    scale_colour_manual(values = c("darkgreen", "darkred", "grey30")) +
    scale_shape_manual(values = c(16, 1, 17)) +
    scale_y_continuous(breaks = c(seq(0, 800, 200))) +
    theme(legend.position = "none") +
    labs(x = NULL, y = "Number of observations")
ggsave("fig_a05.pdf", 
       width = 9, height = 6)



## Robustness: Stronghold counties ----

## update main regression models by only using 
## "stronghold" counties

## strongholds: general elections
lm_cand_share_general_strongholds_base <- update(
    lm_cand_share_general_base,
    data = filter(dat_general,
                  stronghold_dummy == "Stronghold"))


## strongholds: local elections
lm_cand_share_local_strongholds_base <- update(
    lm_cand_share_local_base,
    data = filter(dat_local,
                  stronghold_dummy == "Stronghold"))


## repeat with more extensive model (adding fixed effects)
lm_cand_share_general_strongholds <- update(
    lm_cand_share_general_all,
    data = filter(dat_general,
                  stronghold_dummy == "Stronghold"))


lm_cand_share_local_strongholds <- update(
    lm_cand_share_local_all,
    data = filter(dat_local,
                  stronghold_dummy == "Stronghold"))


## strongholds: general election, government status of candidate's party
lm_govstatus_share_general_strongholds_base <- update(
    lm_govstatus_share_general_base,
    data = filter(dat_general,
                  stronghold_dummy == "Stronghold"))


lm_govstatus_share_general_strongholds <- update(
    lm_govstatus_share_general_all,
    data = filter(dat_general,
                  stronghold_dummy == "Stronghold"))


## Figure A10 ----
dat_eff_share_general_strongholds <- ggpredict(
    lm_cand_share_general_strongholds_base,
    terms = c("winner_loser_before",
              "incumbent"))

plot_interaction(dat_eff_share_general_strongholds) +
    scale_colour_manual(values = c("darkred", "darkgreen")) 
ggsave("fig_a10.pdf", 
       width = 9, height = 3.5)


## Figure A11 ----
dat_eff_share_local_strongholds <- ggpredict(
    lm_cand_share_local_strongholds_base,
    terms = c("winner_loser_before",
              "incumbent"))


plot_interaction(dat_eff_share_local_strongholds) +
    scale_colour_manual(values = c("darkred", "darkgreen"))
ggsave("fig_a11.pdf", 
       width = 9, height = 3.5)





## Figure A12 ----
dat_effect_govstatus_share_general_strongholds <- ggpredict(lm_govstatus_share_general_strongholds_base,
                                                            terms = c("winner_loser_before",
                                                                      "incumbency_status_party")) 


dat_effect_govstatus_share_general_strongholds$winner_loser_untreated <- factor(dat_effect_govstatus_share_general_strongholds$x,
                                                                                levels = c("Defeat", 
                                                                                           "Untreated",
                                                                                           "Win"))

dat_effect_govstatus_share_general_strongholds$group <- relevel(factor(dat_effect_govstatus_share_general_strongholds$group),
                                                                ref = 2)


ggplot(dat_effect_govstatus_share_general_strongholds, 
       aes(x = winner_loser_untreated,
           y = predicted,
           shape = winner_loser_untreated,
           colour = winner_loser_untreated)) +
    geom_hline(yintercept = 0, colour = "grey30", size = 1, 
               linetype = "dashed") +
    facet_grid(~group) +
    geom_linerange(aes(ymin = predicted - 1.96 * std.error,
                       ymax = predicted + 1.96 * std.error),
                   size = 0.5) +
    geom_linerange(aes(ymin = predicted - 1.645 * std.error,
                       ymax = predicted + 1.645 * std.error),
                   size = 1.3) +
    geom_point(size = 4) + 
    scale_colour_manual(values = c("darkred", "darkgreen")) +
    scale_y_continuous(limits = c(-3, 4),
                       breaks = c(seq(-3, 4, 1))) +
    labs(x = NULL, y = "Expected change in vote share\n(percentage points)") +
    theme(legend.position = "none")
ggsave("fig_a12.pdf", 
       width = 9, height = 3.5)


## Table A4 ----
models_strongholds <- list()
models_strongholds[['M1: General elections (incumbency, strongholds)']] <- lm_cand_share_general_strongholds_base
models_strongholds[['M2: General elections (incumbency, strongholds)']] <- lm_cand_share_general_strongholds
models_strongholds[['M3: Local elections (incumbency, strongholds)']] <- lm_cand_share_local_strongholds_base
models_strongholds[['M4: Local elections (incumbency, strongholds)']] <- lm_cand_share_local_strongholds
models_strongholds[['M5: General elections (government status, strongholds)']] <- lm_govstatus_share_general_strongholds_base
models_strongholds[['M6: General elections (government status, strongholds)']] <- lm_govstatus_share_general_strongholds


rename_coefs_strongholds <- c("Intercept" = "(Intercept)",
                              "winner_loser_beforeWin" = "Win (ref. = Defeat)",
                              "incumbentIncumbent (Candidate elected in t-1)" = "Candidate elected in t-1",
                              "winner_loser_beforeWin:incumbentIncumbent (Candidate elected in t-1)" = "Win : Candidate elected in t-1",
                              "incumbency_status_partyParty: Government" = "Candidate's party in government",
                              "winner_loser_beforeWin:incumbency_status_partyParty: Government" = "Win x Candidate's party in government")

rows_add_strongholds <- tribble(~term, ~m1, ~m2, ~m3, ~m4, ~m5, ~m6,
                                'Election FE', '', '✓', '', '✓', '', '✓',
                                'Party FE', '', '✓', '', '✓', '', '✓',
                                'County FE', '', '✓', '', '✓', '', '✓')

attr(rows_add_strongholds, 'position') <- c(11, 12, 13)


modelsummary(models_strongholds,
             add_rows = rows_add_strongholds,
             statistic = "conf.int",
             fmt = "%.2f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_recoded*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs_strongholds,
             gof_omit = "se_type",
             align = "lll")

modelsummary(models_strongholds,
             add_rows = rows_add_strongholds,
             statistic = "conf.int",
             fmt = "%.2f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_recoded*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs_strongholds,
             gof_omit = "se_type",
             align = "llllll",
             output = "tab_a04.docx")



## Robustness: "Unambiguous" county teams ----

## only use candidates who appear once
## some candidates appear twice in the dataset because their 
## constituency lies in two counties (e.g., candidates in constituency
## Carlow-Kilkenny are matched to the Carlow team and the Kilkenny team)
## In the subsequent analyses, we test whether results change
## when we only consider candidates who are matched with a single team


## note: n_obs == 1 filters only candidates who were matched to a single county team
lm_cand_share_general_unambiguous <- update(lm_cand_share_general_all,
                                            data = filter(dat_general,
                                                          n_obs == 1))

lm_cand_share_local_unambiguous <- update(lm_cand_share_general_all,
                                          data = filter(dat_local,
                                                        n_obs == 1))


lm_cand_share_general_unambiguous_base <- update(lm_cand_share_general_base,
                                                 data = filter(dat_general,
                                                               n_obs == 1))

lm_cand_share_local_unambiguous_base <- update(lm_cand_share_general_base,
                                               data = filter(dat_local,
                                                             n_obs == 1))


## Figure A13 ----
dat_eff_share_general_unambiguous <- ggpredict(lm_cand_share_general_unambiguous_base,
                                               terms = c("winner_loser_before",
                                                         "incumbent"))

plot_interaction(dat_eff_share_general_unambiguous)
ggsave("fig_a13.pdf", 
       width = 9, height = 3.5)


## Figure A14 ----
dat_eff_share_local_unambiguous <- ggpredict(lm_cand_share_local_unambiguous_base,
                                             terms = c("winner_loser_before",
                                                       "incumbent"))

plot_interaction(dat_eff_share_local_unambiguous)
ggsave("fig_a14.pdf", 
       width = 9, height = 3.5)


## Table A5 ----
models_unambiguous <- list()
models_unambiguous[['M1: General elections (unambiguous)']] <- lm_cand_share_general_unambiguous_base
models_unambiguous[['M2: General elections (unambiguous)']] <- lm_cand_share_general_unambiguous
models_unambiguous[['M3: Local elections (unambiguous)']] <- lm_cand_share_local_unambiguous_base
models_unambiguous[['M4: Local elections (unambiguous)']] <- lm_cand_share_local_unambiguous


rows_add_unambiguous <- rows_add_4
attr(rows_add_unambiguous, 'position') <- c(11, 12, 13)


modelsummary(models_unambiguous,
             add_rows = rows_add_unambiguous,
             statistic = "conf.int",
             fmt = "%.2f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs,
             gof_omit = "se_type",
             align = "lll")

modelsummary(models_unambiguous,
             add_rows = rows_add_unambiguous,
             statistic = "conf.int",
             fmt = "%.2f",
             stars = c('*' = .05, '**' = .01, '***' = .001),
             coef_omit = "(party_*)|(election_*)|(county_gaa*)|(Intercept*)",
             coef_rename = rename_coefs,
             gof_omit = "se_type",
             align = "lll",
             output = "tab_a05.docx")


## script executed successfully on
date()

sessionInfo()
